<template>
  <div class="countdown">{{ countdown }}</div>
</template>

<script>
export default {
  name: 'countdown',
  props: {
    time: {
      type: String,
      default: ''
    }
  },
  watch: {
    time: {
      immediate: true, // 立即执行 :当刷新页面时会立即执行一次handler函数
      handler (val) {
        this.endTime = val || ''
        this.calcTime()
      }
    }
  },
  data () {
    return {
      endTime: '',
      countdown: '',
      timer: null
    }
  },
  beforeDestroy () {
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    calcTime () {
      this.timer = setInterval(() => {
        const currentTime = new Date().getTime()
        const endTime = new Date(this.endTime).getTime()
        if (endTime < currentTime) {
          this.countdown = '已超时'
          clearInterval(this.timer);
          return
        }
        const countdownTime = (endTime - currentTime) / 1000
        let hour = Math.floor(countdownTime / (60 * 60))
        let min = Math.floor(countdownTime % (60 * 60) / 60)
        let second = Math.floor(countdownTime % 60)
        hour = hour < 10 ? '0' + hour : hour
        min = min < 10 ? '0' + min : min
        second = second < 10 ? '0' + second : second

        this.countdown = `${hour}:${min}:${second}`
      }, 1000)
    },
  }

}
</script>

<style lang='less' scoped>
.countdown {
  display: inline;
  margin-left: 10px;
  font-size: 20px;
  font-weight: 500;
  color: #ed4014;
}
</style>
